$("#zuce-button").click(function () {
  if ($("#zuce-button").text() == '注册') {
    $(".zuce").show()
  } else if ($("#zuce-button").text() == '退出') {
    removeCookie('username')
    $('.denglu-button').html(`<a href="./denglu.html">登录</a>`)
    $('#zuce-button').html(`<a href="zuce.html">注册</a>`)
  }
})



$("#zuce-button").click(function () {
  if ($("#zuce-button").text() == '注册') {
    $('#zuce-button').html(`<a href="zuce.html">注册</a>`)
    console.log(1111);
    $(".shop-car").html(`<div class="jumbotron ">
                  <h1>购物车空空滴！！！！</h1>
                  <p>快去选购吧</p>
                  <p><a class="btn btn-primary btn-lg" href="./shop-list.html" role="button">去商品列表</a></p>
                </div>`
    )
    layer.msg('请先登录', {
      icon: 2,
      time: 1500
    }, function () {
      localStorage.setItem('url', location.href),
        location.href = 'denglu.html'
    })
  } else if ($("#zuce-button").text() == '退出') {
    $('#zuce-button').html(`<a href="javascript:;">注册</a>`)
    
  }
})



if (!username) {
  layer.msg('请先登录', {
    icon: 2,
    time: 1500
  }, function () {
    localStorage.setItem('url', location.href),
      location.href = 'denglu.html'
  })
}


var data = localStorage.getItem('data')
if (!data) {
  $(".shop-car").html(`<div class="jumbotron ">
                  <h1>购物车空空滴！！！！</h1>
                  <p>快去选购吧</p>
                  <p><a class="btn btn-primary btn-lg" href="./shop-list.html" role="button">去商品列表</a></p>
                </div>`
  )
} else {
  var arr = JSON.parse(data).filter(item => item.username == username)
  if (arr.length) {
    var ids = arr.map(item => item.id).join()
    var loadindex = layer.load(2, {
      shade: [1, '#fff']
    })
    $.get('php/shop-car.php', { ids }, res => {
      console.log(res);
      var { meta: { status, msg }, data } = res
      console.log(status);
      console.log(data);
      var str = '';
      console.log(data);
      data.forEach(item => {
        var number = arr.find(v => v.id === item.id).number
        str += `
                    <tr>
                        <td><input checked type="checkbox" name="selectone"></td>
                        <td>
                            <a href="detail.html?id=${item.id}">
                            <img width="80" height="80" src="${item.imgpath.split('=====')[0]}">
                            </a>
                        </td>
                        <td class="price">￥<span>${item.price}</span>元</td>
                        <td class="number">
                            <button class="reduce">-</button>
                            <input size="3" type="number" value="${number}">
                            <button class="add">+</button>
                        </td>
                        <td class="subtotal">￥<span>${item.price * number}</span>元</td>
                        <td data-id="${item.id}">
                            <a href="javascript:;" class="btn removecart btn-danger">删除购物车</a>
                        </td>
                    </tr>
                `
      })
      $(".shop-car tbody").html(str)
      layer.close(loadindex)


      selectAll()
      // 单选功能
      selectOne()
      // 数量加
      numberAdd()
      // 数量减
      numberReduce()
      // 计算小计的功能
      subtotal()
      // 总数量和总价格
      total()
      // 删除购物车功能
      removeCar()
    }, 'json')
  } else {
    $(".shop-car").html(`<div class="jumbotron ">
                  <h1>购物车空空滴！！！！</h1>
                  <p>快去选购吧</p>
                  <p><a class="btn btn-primary btn-lg" href="./shop-list.html" role="button">去商品列表</a></p>
                </div>`
    )
  }
}


function removeCar() {
  $('.removecart').click(function () {
    layer.confirm('你确定要删除吗？', {
      btn: ['确认', '取消'] //按钮
    }, () => {
      $(this).parent().parent().remove()
      total()
      // 删除本地存储中的数据
      var data = localStorage.getItem('data')
      data = JSON.parse(data)
      var id = $(this).parent().attr('data-id')
      var index = data.findIndex(item => item.goodsid === id && username === item.username)
      data.splice(index, 1)
      localStorage.setItem('data', JSON.stringify(data))
      layer.msg('删除成功', {
        time: 1500, //20s后自动关闭
        icon: 1
      });
    }, function () {
      layer.msg('取消成功', {
        time: 1500, //20s后自动关闭
        icon: 1
      });
    });

  })
}
// 总数量和总价格
function total() {
  var totalPrice = 0;
  var totalNum = 0;
  $('[name="selectone"]:checked').each(function (i, v) {
    totalPrice += ($(this).parent().siblings('.subtotal').find('span').text() - 0)
    totalNum += ($(this).parent().siblings('.number').find('input').val() - 0)
  })
  $('.totalNum').text(totalNum)
  $('.totalPrice').text(totalPrice)
}
// 计算小计的功能
function subtotal() {
  $('.shop-car .number input').each(function (i, v) {
    var sub = v.value * $(v).parent().prev().find('span').text()
    $(v).parent().next().find('span').text(sub)
  })
}
// 数量减的功能
function numberReduce() {
  $('.shop-car .number button.reduce').click(function () {
    var number = +$(this).next().val()

    number--
    if (number < 0) {
      number = 0
      return false
    }
    $(this).next().val(number)
    // 修改本地存储中的数据
    var data = localStorage.getItem('data')
    data = JSON.parse(data)
    var id = $(this).parent().siblings().last().attr('data-id')
    var obj = data.find(item => item.id === id && item.username === username)
    obj.number--;

    localStorage.setItem('data', JSON.stringify(data))
    subtotal()
    total()
  })
}
// 数量加功能
function numberAdd() {
  $('.shop-car .number button.add').click(function () {
    var number = +$(this).prev().val()
    number++
    $(this).prev().val(number)
    // 修改本地存储中的数据
    var data = localStorage.getItem('data')
    data = JSON.parse(data)
    var id = $(this).parent().siblings().last().attr('data-id')
    var obj = data.find(item => item.id === id && item.username === username)
    obj.number++;
    localStorage.setItem('data', JSON.stringify(data))
    subtotal()
    total()
  })
}
// 单选功能
function selectOne() {
  $('[name="selectone"]').click(function () {
    var arr = Array.prototype.slice.call($('[name="selectone"]'))
    var bool = arr.every(item => item.checked)
    $('[name="selectAll"]').prop('checked', bool)
    total()
  })
}
// 全选功能
function selectAll() {
  $('[name="selectAll"]').click(function () {
    $('[name="selectone"]').prop('checked', $(this).prop('checked'))
    $('[name="selectAll"]').prop('checked', $(this).prop('checked'))
    total()
  })
}